package me.jiatao.paging3.network.retrofit

import com.google.gson.GsonBuilder
import me.jiatao.paging3.BuildConfig
import me.jiatao.paging3.network.WanAndroidApi
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class RetrofitClient private constructor() {
    private fun getOkHttpClient(): OkHttpClient {
        /**
         * 日志拦截器
         */
        val loggingInterceptor = HttpLoggingInterceptor()
        // 包含header、body数据
        if (BuildConfig.DEBUG) {
            loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        } else {
            loggingInterceptor.level = HttpLoggingInterceptor.Level.NONE
        }

        /**
         * Header拦截器
         */
        val headerInterceptor = Interceptor { chain ->
            val request = chain.request()
                .newBuilder()
                .addHeader("Content_Type", "application/json")
                .addHeader("charset", "UTF-8")
                .build()

            chain.proceed(request)
        }

        return OkHttpClient()
            .newBuilder()
            .connectTimeout(30, TimeUnit.SECONDS) //设置超时时间
            .readTimeout(10, TimeUnit.SECONDS) //设置读取超时时间
            .writeTimeout(10, TimeUnit.SECONDS)
            .addInterceptor(loggingInterceptor)
            .addInterceptor(headerInterceptor)
            .build()
    }

    private fun getRetrofit(): Retrofit {
        /**
         * 自定义Gson配置
         */
        val gson = GsonBuilder()
            .serializeNulls()
            .create()

        return Retrofit.Builder()
            .baseUrl(HttpConst.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(getOkHttpClient())
            .build()
    }


    companion object {
        private val instance: RetrofitClient by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            RetrofitClient()
        }

        private fun <T> createApi(cls: Class<T>): T {
            return instance.getRetrofit().create(cls)
        }

        val wanAndroidApi: WanAndroidApi by lazy {
            createApi(WanAndroidApi::class.java)
        }
    }
}